package org.strongme.modules.sys.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.strongme.common.persistence.Page;
import org.strongme.common.web.BaseController;
import org.strongme.config.Global;
import org.strongme.modules.sys.entity.Role;
import org.strongme.modules.sys.entity.User;
import org.strongme.modules.sys.service.SystemService;
import org.strongme.modules.sys.utils.UserUtils;
import org.strongme.util.StringUtils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@Controller
@RequestMapping(value = "sys/user")
public class UserController extends BaseController {

	@Autowired
	private SystemService systemService;

	@ModelAttribute
	public User get(@RequestParam(required = false) String id) {
		User u = null;
		if (StringUtils.isNotBlank(id)) {
			u = systemService.getUser(id);
		}else {
			u = new User();
		}
		return u;
	}
	
	/**
	 * 列出当前登录用户所在驾校的所有用户,包括当前学习所有用户、当前部门所有用户、当前职位所有用户
	 * @param user
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = { "list", ""})
	public String list(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		 Page<User> page = systemService.findUser(new Page<User>(request,
		 response), user);
		 model.addAttribute("page", page);
		return "modules/sys/user/userList.jsp";
	}
	
	/**
	 * 前往用户编辑页面
	 * @param user
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "form")
	public String form(User user, Model model) {
		model.addAttribute("user", user);
		model.addAttribute("menuList", systemService.findAllMenu());
		model.addAttribute("roleList", systemService.findAllRole());
		return "modules/sys/user/userForm.jsp";
	}
	
	/**
	 * 保存用户信息
	 * @param user
	 * @param request
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "save")
	public String save(User user, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
		
		if(user.getId()!=null&&!"".equals(user.getId())) {
			// 如果新密码为空，则不更换密码
			if (StringUtils.isNotBlank(user.getNewPassword())) {
				user.setPassword(SystemService.entryptPassword(user.getNewPassword()));
			}
		}else {
			user.setPassword(SystemService.entryptPassword(Global.getConfig("default.password")));
		}
		if (!beanValidator(model, user)){
			return form(user, model);
		}
		if (!"true".equals(checkLoginName(user.getOldName(), user.getName()))){
			addMessage(model, "保存用户'" + user.getName() + "'失败，登录名已存在");
			return form(user, model);
		}
		// 角色数据有效性验证，过滤不在授权内的角色
		List<Role> roleList = Lists.newArrayList();
		List<String> roleIdList = user.getRoleIdList();
		for (Role r : systemService.findAllRole()){
			if (roleIdList.contains(r.getId())){
				roleList.add(r);
			}
		}
		user.setRoleList(roleList);
		// 保存用户信息
		systemService.saveUser(user);
		// 清除当前用户缓存
		if (user.getName().equals(UserUtils.getUser().getName())){
			UserUtils.clearCache();
			UserUtils.clearCache(user);
		}
		addMessage(redirectAttributes, "保存用户'" + user.getName() + "'成功");
		return "redirect:/sys/user/list?repage";
	}
	
	@RequestMapping(value = "delete")
	public String delete(User user, RedirectAttributes redirectAttributes) {
			if(user.getId()!=null && user.getId().equals(UserUtils.getUser().getId())) {
				addMessage(redirectAttributes, "删除用户失败，无法删除当前登陆用户");
			}else {
				systemService.deleteUser(user);
				addMessage(redirectAttributes, "删除用户成功");
			}
		return "redirect:/sys/user/list";
	}
	
	
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = { "listData" })
	public Page<User> listData(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<User> page = systemService.findUser(new Page<User>(request, response), user);
		return page;
	}

    /**
     * 验证登录名是否有效
     * @param oldName
     * @param name
     * @return
     */
	@ResponseBody
	@RequestMapping(value = "checkLoginName")
	public String checkLoginName(String oldName, String name) {
		if (name != null && name.equals(oldName)) {
			return "true";
		} else if (name != null && systemService.getUserByLoginName(name) == null) {
			return "true";
		}
		return "false";
	}
	
	/**
	 * 检测驾校使用的手机号是否已经被使用了
	 * @param mobile
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "checkMobile")
	public String checkSchoolMobile(String mobile) {
		String result = "true";
		if(!UserUtils.checkMobile(mobile)) {
			result = "false";
		}
		return result;
	}
	
	/**
	 * 检测后台用户邮箱是否被注册
	 * @param email
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "checkEmail")
	public String checkEmail(String email) {
		String result = "true";
		if(!UserUtils.checkEmail(email)) {
			result = "false";
		}
		return result;
	}
	
	/**
	 * 修改个人用户密码
	 * @param oldPassword
	 * @param newPassword
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "modifyPwd")
	public String modifyPwd(String oldPassword, String newPassword, Model model) {
		User user = UserUtils.getUser();
		if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)){
			if (SystemService.validatePassword(oldPassword, user.getPassword())){
				systemService.updatePasswordById(user.getId(), user.getName(), newPassword);
				model.addAttribute("message", "修改密码成功");
			}else{
				model.addAttribute("message", "修改密码失败，旧密码错误");
			}
		}
		model.addAttribute("user", user);
		return "modules/sys/user/userModifyPwd.jsp";
	}


    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeData")
    public List<Map<String, Object>> treeData(HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<User> list = Lists.newArrayList();
        for (int i = 0; i < list.size(); i++) {
            User e = list.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", "u_" + e.getId());
            map.put("pId", 0);
            map.put("name", StringUtils.replace(e.getName(), " ", ""));
            mapList.add(map);
        }
        return mapList;
    }

}
